#! /usr/bin/env python
# coding=utf-8
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Author: senlin
# Create: 2021-06-28
# ******************************************************************************/
"""
This is a simple defined class to get the list of differences between package name and source package name
"""
import sys
sys.path.append('/home/oect')
import argparse
import codecs
import csv
from src.libs.logger import logger
from src.config import constant
from src.community.openeuler_community_info_query import OpenEulerCommunityRepoInfoQuery
import re
import os
from src.libs.yamlfunc import YamlReadAndWrite
from src.api.obs import OpensuseObsAPI
from src.libs.base import replase

class PackageDifferFromSRPM(object):
    """
    get sig maintainer and contributor of package
    """
    def __init__(self, account, password):
        """
        """
        self.obs_api = OpensuseObsAPI(account = account, password = password)

    def _get_real_packge_name(self, srpm_name):
        """
        @description : get the real package name in gitee
        -----------
        @param :
        -----------
        @returns :
        -----------
        """

    def _get_package_2_srpm(self, obs_project, package_list_file = None):
        """
        @description : Get the  package name and SRPM registration in the obs_project
        -----------
        @param :
        -----------
        @returns :
        -----------
        """
        res_csv_name = obs_project.replace(':', '_') + '.csv'
        pkg_srpm = dict()
        pkg_list = []
        if package_list_file:
            res_csv_name = '_'.join(['res', package_list_file])
            with open(package_list_file, 'r') as file:
                data = file.readlines()
                for line in data:
                    pkg_list.append(line.strip())
        else:
            pkg_list = self.obs_api.get_source_package_of_project(obs_project)

        with codecs.open(res_csv_name, 'w', 'utf-8') as result_file:
            writer = csv.writer(result_file)
            writer.writerow(["Package", "Source"])
            for pkg in pkg_list:
                # cmd = "osc api \/build\/%s/standard_aarch64/aarch64/%s | grep '\.src'" % (obs_project, pkg)
                # srpm = os.popen(cmd).read()
                

                # if not srpm:
                #     cmd = "osc api \/build\/%s/standard_x86_64/x86_64/%s | grep '\.src'" % (obs_project, pkg)
                #     srpm = os.popen(cmd).read()
                #     if not srpm:
                #         logging.error("No binary of %s", pkg)
                #         srpm = "NA"
                #         pkg_srpm["repos"][pkg] = dict()
                #         pkg_srpm["repos"][pkg]['srpm'] = srpm
                #         pkg_srpm["repos"][pkg]['spec'] = srpm
                #         continue

                # logging.info("cmd get srpm: %s", re.findall(r"\"(.+?).src.rpm", srpm))

                # srpm = re.findall(r"\"(.+?).src.rpm", srpm)[0]
                # cmd = "echo %s | sed -r 's/(-[^-]+){2}$//'" % (srpm)
                # srpm = os.popen(cmd).read().split('\n')[0]

                srpm = self.obs_api.published_packages(obs_project, pkg)
                if srpm is None:
                    srpm = self.obs_api.published_packages(obs_project, pkg, repository = "standard_x86_64", arch = "x86_64")
                    if srpm is None:
                        continue
                source_name = replase(srpm)
                logger.info(f"pkg: {pkg}, srpm name: {srpm}, source_name:{source_name}")
                writer.writerow([pkg, source_name])

        return

def main(obs_project):
    """
    main func
    """
    test_pdfs = PackageDifferFromSRPM("senlin", "xsl***2021")
    test_pdfs._get_package_2_srpm(obs_project)
    # YamlReadAndWrite(constant.LOCAL_REPO_EXCEP).write_yaml(pkg_srpm)


if __name__ == "__main__":
    """ parser = argparse.ArgumentParser()
    parser.add_argument("obs_project", type=str, help="The Package to be Queried")
    parser.add_argument("-l", "--package_list", default=None, nargs="?", required=True,
                        help="input the list for scanning.")
    args = parser.parse_args() """

    main("openEuler:22.03:LTS")
    # pkg_srpm = dict()
    # pkg_srpm["repos"]=dict()
    # pkg_srpm["repos"]["aaa"] = dict()
    # pkg_srpm["repos"]["aaa"]['srpm'] = "bbb"
    # pkg_srpm["repos"]["aaa"]['spec'] = "srpm"

    # YamlReadAndWrite('pdfs.yaml').write_yaml(pkg_srpm)

